package com.example.myproject.service;

import com.example.myproject.dto.AnalyseResponse;
import com.example.myproject.mapper.AnalyseMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class AnalyseService {

    private final AnalyseMapper analyseMapper;

    public AnalyseService(AnalyseMapper analyseMapper) {
        this.analyseMapper = analyseMapper;
    }

    public AnalyseResponse getAnalyse(Long userId) {
        Long totalDownload = analyseMapper.getTotalDownload();
        Long totalTorrentCount = analyseMapper.getTotalTorrentCount();
        Long activeUserCount = analyseMapper.getActiveUserCount();

        List<Map<String, Object>> userStatsRaw = analyseMapper.getUserMonthlyStats(userId);
        List<Map<String, Object>> allStatsRaw = analyseMapper.getAllMonthlyStats();

        AnalyseResponse res = new AnalyseResponse();
        res.setTotalDownload(totalDownload);
        res.setTotalTorrentCount(totalTorrentCount);
        res.setActiveUserCount(activeUserCount);

        res.setUserMonthlyUpload(extractList(userStatsRaw, "upload_sum"));
        res.setUserMonthlyDownload(extractList(userStatsRaw, "download_sum"));

        res.setAllMonthlyUpload(extractList(allStatsRaw, "upload_sum"));
        res.setAllMonthlyDownload(extractList(allStatsRaw, "download_sum"));

        return res;
    }

    private List<Long> extractList(List<Map<String, Object>> rawList, String key) {
        List<Long> list = new ArrayList<>();
        if (rawList == null) {
            for (int i = 0; i < 4; i++) {
                list.add(0L);
            }
            return list;
        }
        int fillCount = 4 - rawList.size();
        // 先补0（最早月份）
        for (int i = 0; i < fillCount; i++) {
            list.add(0L);
        }
        // 反转顺序保证最早月份在前面
        for (int i = rawList.size() - 1; i >= 0; i--) {
            Number val = (Number) rawList.get(i).get(key);
            list.add(val == null ? 0L : val.longValue());
        }
        return list;
    }
}
